package com.hmall.gateway.filters;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    //没有注册为spring的bean，无法注入
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        //2.判断是否拦截
        if(isIn(path)){
            return chain.filter(exchange);
        }
        //3.获取token
        String token=null;
        List<String> authorization = request.getHeaders().get("Authorization");
        if(!CollUtil.isEmpty(authorization)){
            token = authorization.get(0);
        }
        //4.解析token
        Long userId=null;
        try {
            userId  = jwtTool.parseToken(token);
        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.
        String userIdString = userId.toString();
        ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", userIdString)).build();

        //6.放行
        return chain.filter(ex);
    }
    private boolean isIn(String path){
        for (String excludePath : authProperties.getExcludePaths()){
            //注意方法参数的顺序
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }
}
